/**
 * Copyright Marvell Inc
 */

package com.hisense.settings.parental;

import java.util.LinkedList;
import java.util.List;

import android.content.Context;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.CheckedTextView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.settings.R;
import com.hisense.settings.base.TVBaseDialog;
import com.hisense.settings.util.HisUtils;
import com.hisense.settings.util.Wrapper;
import com.hisense.settings.widget.ToastCreator;
/*import com.marvell.willowtv.framework.features.LiveTv;
import com.marvell.willowtv.framework.features.TvFramework;
import com.marvell.willowtv.framework.model.atsc.USDTVServiceId;
import com.marvell.willowtv.framework.util.atsc.ChannelEnumClass;
import com.marvell.willowtv.framework.util.atsc.ChannelEnumClass.ChannelDetails;
import com.marvell.willowtv.framework.util.atsc.ChannelEnumClass.ChannelListElement;
import com.marvell.willowtv.framework.util.atsc.ChannelEnumClass.ServiceModificationFlags;*/

/**
 * Activity for displaying channel list
 * 
 * @author Davinder
 * @version 1.1
 */
public class ChannelLocksActivity extends TVBaseDialog {

    private static final String TAG = "ChannelLocksActivity";
    private Resources mRes = null;
    private ListView mListView = null;
    private int mSelectedId = 0;
    //public  LinkedList<ChannelListElement> serviceList = null;
    DeviceListAdapter mDeviceAdapter = null;
    private int mFocusPosition = 0;
    private Handler mHandler = new Handler();
    private Runnable mRunnable = null;
    //private final LiveTv gLive = TvFramework.getInstance().getLiveTvInstance();
    
    /**
     * Called when the activity is first created.
     * 
     * @param savedInstanceState of type Bundle
     */
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate()");
       /* mRes = getResources();
        
        int serviceFlag = 0;
        boolean lock = false;

        final List<ChannelDetails> channelInfo = gLive.getChannelList();
        if (channelInfo == null || channelInfo.isEmpty()) {
            Log.e(TAG, "No channel List available");
            new ToastCreator(getApplicationContext(), mRes.getString(R.string.NoChannelListAvailable),
                    R.drawable.info).showToast();
        }
        int size = 0;
        if (channelInfo != null) {
            size = channelInfo.size();
        }
        ChannelDetails chDetails = null;
        ChannelDetails currentChannel = gLive.getCurrentChannelDetail();
        serviceList = new LinkedList<ChannelListElement>();
	
        for (int i = 0; i < size; i++) {
            Log.d(TAG, " Index of loop***** " + i);
            chDetails = channelInfo.get(i);

            serviceFlag = chDetails.getServiceFlag();
            if ((serviceFlag & ServiceModificationFlags.Lock_Flag) == ServiceModificationFlags.Lock_Flag) {
                lock = true;
            } else {
                lock = false;
            }
            ChannelListElement listElement = new ChannelEnumClass().new ChannelListElement(
                    chDetails);
            listElement.setChannelLockStatus(lock);
            serviceList.add(listElement);
            if (Wrapper.getWrapperInstance().isSameChannel(currentChannel, chDetails)) {
                    mFocusPosition = i;
                }
            }*/
        setContentView(R.layout.channel_list);
        setTimeOut(HisUtils.ONE_MINUTE * 2);


        /*if (size > 0) {

            mListView = (ListView) findViewById(R.id.channel_list);
            mDeviceAdapter = new DeviceListAdapter(this);
            mListView.setAdapter(mDeviceAdapter);
            mListView.setSelection(mFocusPosition);
			
			mListView.setOnItemClickListener(new OnItemClickListener(){
				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					updateLockStatusToPlatform(position);
					mDeviceAdapter.notifyDataSetChanged();
				}					
			});
            mListView.setOnItemSelectedListener(new OnItemSelectedListener(){

                @Override
                public void onItemSelected(AdapterView<?> arg0, View arg1,
                        int arg2, long arg3) {
                    mSelectedId = mListView.getSelectedItemPosition();
                }

                @Override
                public void onNothingSelected(AdapterView<?> arg0) {
                    // TODO Auto-generated method stub
                }
            });
        }*/
     }


    /**
     * Called when a key was released .
     * 
     * @param keyCode integer for the corresponding key
     * @param event KeyEvent occured
     * @return boolean true if key is handled
     */
    @Override
    public boolean onKeyUp(final int keyCode, final KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_PROG_RED 
                || keyCode == KeyEvent.KEYCODE_DPAD_CENTER 
                || keyCode == KeyEvent.KEYCODE_ENTER) {
            updateLockStatusToPlatform(mSelectedId);
            mDeviceAdapter.notifyDataSetChanged();
            return super.onKeyUp(keyCode, event);
            
        } else {
            return super.onKeyUp(keyCode, event);
        }
    }

    /**
     * To check channel lock status of the selected channel from service list
     * 
     * @return channel lock status
     */
    private boolean checkChannelLockState(int channelId) {

        /*Log.d(TAG, "checkChannelLockState()");

        int serviceFlag = -1;
        ChannelListElement selectedItem = serviceList.get(channelId);
        serviceFlag = selectedItem.getServiceFlag();

        if ((serviceFlag & ServiceModificationFlags.Lock_Flag) == ServiceModificationFlags.Lock_Flag) {
            return true;
        }*/
        return false;
    }

    /**
     * Method to toggle channel lock status for selected service. *
     * 
     * @return channel lock status
     */
    private void updateLockStatusToPlatform(int channelId) {

        Log.d(TAG, "updateLockStatusToPlatform()");
        /*ChannelListElement selectedItem = serviceList.get(channelId);
        
        int serviceFlag = selectedItem.getServiceFlag();

        serviceFlag = serviceFlag ^ ServiceModificationFlags.Lock_Flag;
        
        TvFramework.getInstance().getLiveTvInstance().modifyService(selectedItem.getServiceId(), serviceFlag);

        
        selectedItem.setServiceFlag(serviceFlag);
        selectedItem.setChannelLockStatus(!selectedItem.getChannelLockStatus());*/
    }

    /**
     * Switch channel according to the id in channel list
     */
    public void switchChannel(int channelId) {

        /*Log.d(TAG, "switchChannel " + channelId);
        try {
            ChannelDetails currentChannel = gLive.getCurrentChannelDetail();
            ChannelListElement selectedItem = serviceList.get(channelId);
            int majorNumber = selectedItem.getMajorNo();
            int minorNumber = selectedItem.getMinorNo();
            USDTVServiceId serviceId = selectedItem.getServiceId();
            if (!Wrapper.getWrapperInstance().isSameChannel(currentChannel, selectedItem)) {
                Wrapper.getWrapperInstance().pauseCC();
                gLive.channelChange(true, majorNumber, minorNumber, serviceId);
            }
        } catch (NumberFormatException e) {
            //ProgramaticException.displayException(getApplicationContext(), TAG, e);
			Log.e(TAG, "switchChannel error: " + e);
        }*/
    }

    /**
     * Override method called when activity gets closed
     */
    public void onDestroy() {

        Log.d(TAG, "onDestroy()");

        super.onDestroy();
    }
	
	
	private class DeviceListAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
	
		public DeviceListAdapter(Context context) {
			mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}
	
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			//return serviceList.size();
			 return 6;
		}
	
		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return arg0;
		}
	
		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}
	
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder;
			Log.d(TAG, "&&&&&&&&&&&&&&&6^^6^^6^^6^^6^^6^^6^^6^^6^^6^^6^^6^^6^^6^^position "+ position);
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.channel_list_item,
						null);
				holder.channel_number = (TextView) convertView.findViewById(R.id.channel_number);
				holder.channel_name = (TextView) convertView.findViewById(R.id.title);
				holder.selectlabelView = (CheckedTextView) convertView.findViewById(R.id.selectlabel);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
	
			/*if (holder != null && holder.channel_number != null) {
				// holder.channel_number.setText(mList[position]);
				holder.channel_number.setText(serviceList.get(position).getChannelNumber(
						mRes.getInteger(R.integer.invalid_major_no)));
			}
			if (holder != null && holder.channel_name != null) {
				// holder.channel_name.setText(mList[position]);
				String str = serviceList.get(position).getChannelName();
				if (str.length() > 25) {
					str = new StringBuffer(str).substring(0, 25).concat("...");
				}
				holder.channel_name.setText(str);
			}
			
			boolean lock = serviceList.get(position).getChannelLockStatus();
			if (holder != null && holder.selectlabelView != null) {
				holder.selectlabelView.setChecked(lock);
			}*/
			
			// holder.selectlabelView.setBackgroundResource(R.drawable.lock_icon);
			return convertView;
		}
	
		class ViewHolder {
			TextView channel_number;
			TextView channel_name;
			CheckedTextView selectlabelView;
		}
	}
}
